
import { addData } from './addData';
import { getDataById } from './getDataById';
import { updateDB } from './updateDB';
import { getDataByIndex } from './getDataByIndex';
import { getDataAll } from './getDataAll';
import { deleteDB } from './deleteDB';
import { getDataLikeCursor } from './getDataLikeCursor';
import { resultFomat, randomId ,createDB , createTime} from './index';

export const storeName = 'info';

/**
 * 添加或更新数据
 * @param {*} data
 * @returns
 */
export async function insertInfoDataItem(data) {
  const db = await createDB(storeName);
  const data_ = data.id ? await getDataById(db, storeName, data.id) : null;
  // 如果该主键对应的数据已存在，则做更新操作
  if (data_) {
    return updateDB(db, storeName, data);
  }
  return addData(db, storeName, {...data,id:randomId(),createTime:createTime()});
}

/**
 * 根据id获取数据
 * @param {*} id
 * @returns
 */
export async function getInfoDataById(id) {
  const db = await createDB(storeName);
  const data_ = await getDataById(db, storeName, id);
  // 设置了有效期，且已过期，则删除数据
  if (data_?.expire && data_.expire < new Date().getTime()) {
    await deleteDB(db, storeName, id);
    return;
  }
  return resultFomat(data_, 'data', 'ok');
}

/**
 * 根据索引查询数据
 * @param {*} indexName
 * @param {*} indexValue
 * @returns
 */
export async function getInfoDataByIndex(indexName, indexValue) {
  const db = await createDB(storeName);
  const data_ = await getDataByIndex(db, storeName, indexName, indexValue);
  return resultFomat(data_, 'data');
}

/**
 * 模糊查询
 * @param { string } params 
 * @returns 
 */
export async function getInfoDataLike(params) {
  const key = 'title';
  const db = await createDB(storeName);
  const data_ = await getDataLikeCursor(db, storeName, {
    title: params[key]
  });
  return resultFomat(data_,'rows')
}

/**
 * 获取全部数据
 * @returns
 */
export async function getInfoDataAll() {
  const db = await createDB(storeName);
  const data_ = await getDataAll(db, storeName);
  return resultFomat(data_, 'rows');
}

/**
 * 根据id删除
 * @param {*} id 主键id
 * @returns
 */
export async function deleteInfoDataItemByID(id) {
  const db = await createDB(storeName);
  const data_ = await deleteDB(db, storeName, id);
  return resultFomat(data_, 'data', 'ok');
}

/**
 * 获取前五条数据的banner
 * @returns 
 */
export async function getInfoTop5Banner() {
  const db = await createDB(storeName);
  const data_ = await getDataAll(db, storeName);
  const top5Data = data_.splice(0, 5);
  return resultFomat(top5Data, 'rows');
}


/**
 * 获取前4条数据
 * @returns 
 */
export async function getInfoTop4() {
  const db = await createDB(storeName);
  const data_ = await getDataAll(db, storeName);
  const top5Data = data_.splice(0, 4);
  return resultFomat(top5Data, 'rows');
}

